﻿//"The contents of this file are subject to the Mozilla Public License
//Version 1.1 (the "License"); you may not use this file except in
//compliance with the License. You may obtain a copy of the License at
//http://www.mozilla.org/MPL/

//Software distributed under the License is distributed on an "AS IS"
//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//License for the specific language governing rights and limitations
//under the License.

//The Original Code is TSharp.

//The Initial Developer of the Original Code is Mar3ek (http://mar3ek.wordpress.com).
//Portions created by Mar3ek are Copyright (C) 2010
//Mar3ek (http://mar3ek.wordpress.com). All Rights Reserved.

//Contributor(s): ______________________________________.

//Alternatively, the contents of this file may be used under the terms
//of the _____ license (the  "[___] License"), in which case the
//provisions of [______] License are applicable instead of those
//above.  If you wish to allow use of your version of this file only
//under the terms of the [____] License and not to allow others to use
//your version of this file under the MPL, indicate your decision by
//deleting  the provisions above and replace  them with the notice and
//other provisions required by the [___] License.  If you do not delete
//the provisions above, a recipient may use your version of this file
//under either the MPL or the [___] License."

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Linq;

namespace TSharp
{
    public partial class Twitter
    {
        #region List subscribers

        #region GetListSubscribers

        /// <summary>
        /// Returns the subscribers of the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listSlug">The slug of the target list</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>List of users</returns>
        public Collection<TwitterUser> GetListSubscribers(string screenName, string listSlug)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (string.IsNullOrEmpty(listSlug)) throw new ArgumentNullException("listSlug");

            var result = SendRequest(RequestMethod.Get,
                                        string.Format("https://api.twitter.com/1/{0}/{1}/subscribers.xml", screenName,
                                                      listSlug),
                                        true);

            var doc = XDocument.Parse(result);
            var usersList = doc.Element("users_list");

            var listSubscribers = new Collection<TwitterUser>();
            // ReSharper disable PossibleNullReferenceException
            if (usersList != null)
                listSubscribers = new Collection<TwitterUser>(usersList.Element("users").Elements("user").Select(ParseAuthor).ToList());
            // ReSharper restore PossibleNullReferenceException
            return listSubscribers;
        }

        /// <summary>
        /// Returns the subscribers of the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listId">The ID of the target list</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>List of users</returns>
        public Collection<TwitterUser> GetListSubscribers(string screenName, ulong listId)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (listId < 1) throw new ArgumentOutOfRangeException("listId");

            var result = SendRequest(RequestMethod.Get,
                                        string.Format("https://api.twitter.com/1/{0}/{1}/subscribers.xml", screenName,
                                                      listId),
                                        true);

            var doc = XDocument.Parse(result);
            var usersList = doc.Element("users_list");

            var listSubscribers = new Collection<TwitterUser>();
            if (usersList != null)
                // ReSharper disable PossibleNullReferenceException
                listSubscribers = new Collection<TwitterUser>(usersList.Element("users").Elements("user").Select(ParseAuthor).ToList());
            // ReSharper restore PossibleNullReferenceException
            return listSubscribers;
        }

        /// <summary>
        /// Returns the subscribers of the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listId">The ID of the target list</param>
        /// <param name="cursor">Breaks the results into pages. Provide a value of -1 to begin paging</param>
        /// <param name="previousCursor">Start index if the previous page</param>
        /// <param name="nextCursor">Start index of the next page</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <returns>List of users</returns>
        public Collection<TwitterUser> GetListSubscribers(string screenName, ulong listId, long cursor,
                                                    out long previousCursor, out long nextCursor)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (listId < 1) throw new ArgumentOutOfRangeException("listId");
            if (cursor < -1) throw new ArgumentOutOfRangeException("cursor");

            var result = SendRequest(RequestMethod.Get,
                                        string.Format("https://api.twitter.com/1/{0}/{1}/subscribers.xml", screenName,
                                                      listId),
                                        true,
                                        new KeyValuePair<string, string>("cursor", cursor.ToString()));

            var doc = XDocument.Parse(result);
            var usersList = doc.Element("users_list");

            var users = new Collection<TwitterUser>();
            previousCursor = 0;
            nextCursor = 0;
            if (usersList != null)
            {
                // ReSharper disable PossibleNullReferenceException
                users = new Collection<TwitterUser>(usersList.Element("users").Elements("user").Select(ParseAuthor).ToList());

                nextCursor = long.Parse(usersList.Element("next_cursor").Value);
                previousCursor = long.Parse(usersList.Element("previous_cursor").Value);
                // ReSharper restore PossibleNullReferenceException
            }
            return users;
        }

        /// <summary>
        /// Returns the subscribers of the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listSlug">The slug of the target list</param>
        /// <param name="cursor">Breaks the results into pages. Provide a value of -1 to begin paging</param>
        /// <param name="previousCursor">Start index if the previous page</param>
        /// <param name="nextCursor">Start index of the next page</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <returns>List of users</returns>
        public Collection<TwitterUser> GetListSubscribers(string screenName, string listSlug, long cursor,
                                                    out long previousCursor, out long nextCursor)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (string.IsNullOrEmpty(listSlug)) throw new ArgumentOutOfRangeException("listSlug");
            if (cursor < -1) throw new ArgumentOutOfRangeException("cursor");

            var result = SendRequest(RequestMethod.Get,
                                        string.Format("https://api.twitter.com/1/{0}/{1}/subscribers.xml", screenName,
                                                      listSlug),
                                        true,
                                        new KeyValuePair<string, string>("cursor", cursor.ToString()));

            var doc = XDocument.Parse(result);
            var usersList = doc.Element("users_list");

            var users = new Collection<TwitterUser>();
            nextCursor = 0;
            previousCursor = 0;
            if (usersList != null)
            {
                // ReSharper disable PossibleNullReferenceException
                users = new Collection<TwitterUser>(usersList.Element("users").Elements("user").Select(ParseAuthor).ToList());

                nextCursor = long.Parse(usersList.Element("next_cursor").Value);
                previousCursor = long.Parse(usersList.Element("previous_cursor").Value);
                // ReSharper restore PossibleNullReferenceException
            }
            return users;
        }

        /// <summary>
        /// Returns the subscribers of the specified list.
        /// </summary>
        /// <param name="list">List of which to retrieve users</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>List of users</returns>
        public Collection<TwitterUser> GetListSubscribers(TwitterList list)
        {
            if (list == null) throw new ArgumentNullException("list");
            return GetListSubscribers(list.Owner.ScreenName, list.Slug);
        }

        /// <summary>
        /// Returns the subscribers of the specified list.
        /// </summary>
        /// <param name="list">List of which to retrieve users</param>
        /// <param name="cursor">Breaks the results into pages. Provide a value of -1 to begin paging</param>
        /// <param name="previousCursor">Start index if the previous page</param>
        /// <param name="nextCursor">Start index of the next page</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>List of users</returns>
        public Collection<TwitterUser> GetListSubscribers(TwitterList list, long cursor, out long previousCursor,
                                                    out long nextCursor)
        {
            if (list == null) throw new ArgumentNullException("list");
            return GetListSubscribers(list.Owner.ScreenName, list.Slug, cursor, out previousCursor, out nextCursor);
        }

        #endregion

        #region FollowList

        /// <summary>
        /// Makes the authenticated user follow the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listSlug">The slug of the target list</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>Followed list</returns>
        public TwitterList FollowList(string screenName, string listSlug)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (string.IsNullOrEmpty(listSlug)) throw new ArgumentNullException("listSlug");

            var result = SendRequest(RequestMethod.Post,
                                        string.Format("https://api.twitter.com/1/{0}/{1}/subscribers.xml", screenName,
                                                      listSlug),
                                        false);

            var doc = XDocument.Parse(result);

            return ParseList(doc.Element("list"));
        }

        /// <summary>
        /// Makes the authenticated user follow the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listId">The ID of the target list</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>Followed list</returns>
        public TwitterList FollowList(string screenName, ulong listId)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (listId < 1) throw new ArgumentOutOfRangeException("listId");

            var result = SendRequest(RequestMethod.Post,
                                        string.Format("https://api.twitter.com/1/{0}/{1}/subscribers.xml", screenName,
                                                      listId),
                                        false);

            var doc = XDocument.Parse(result);

            return ParseList(doc.Element("list"));
        }

        /// <summary>
        /// Makes the authenticated user follow the specified list.
        /// </summary>
        /// <param name="list">The list to follow</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>Followed list</returns>
        public TwitterList FollowList(TwitterList list)
        {
            if (list == null) throw new ArgumentNullException("list");

            return FollowList(list.Owner.ScreenName, list.Id);
        }

        #endregion


        /// <summary>
        /// Unsubscribes the authenticated user form the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listSlug">The slug of the target list</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>Unsubscribed list</returns>
        public TwitterList UnfollowList(string screenName, string listSlug)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (string.IsNullOrEmpty(listSlug)) throw new ArgumentNullException("listSlug");

            var result = SendRequest(RequestMethod.Delete,
                                        string.Format("https://api.twitter.com/1/{0}/{1}/subscribers.xml", screenName,
                                                      listSlug),
                                        false);

            var doc = XDocument.Parse(result);

            return ParseList(doc.Element("list"));
        }

        /// <summary>
        /// Unsubscribes the authenticated user form the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listId">The ID of the target list</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>Unsubscribed list</returns>
        public TwitterList UnfollowList(string screenName, ulong listId)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (listId < 1) throw new ArgumentOutOfRangeException("listId");

            var result = SendRequest(RequestMethod.Delete,
                                        string.Format("https://api.twitter.com/1/{0}/{1}/subscribers.xml", screenName,
                                                      listId),
                                        false);

            var doc = XDocument.Parse(result);

            return ParseList(doc.Element("list"));
        }

        /// <summary>
        /// Unsubscribes the authenticated user form the specified list.
        /// </summary>
        /// <param name="list">List from which to unsubscribe</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>Unsubscribed list</returns>
        public TwitterList UnfollowList(TwitterList list)
        {
            if (list == null) throw new ArgumentNullException("list");

            return UnfollowList(list.Owner.ScreenName, list.Id);
        }

        /// <summary>
        /// Checks if a user is a subscriber of the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listSlug">The slug of the target list</param>
        /// <param name="targetUserId">The user ID of the potential list subscriber</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <returns>True if the user is a subscriber of the list, otherwise false</returns>
        public bool IsUserSubscriberOfList(string screenName, string listSlug, ulong targetUserId)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (string.IsNullOrEmpty(listSlug)) throw new ArgumentNullException("listSlug");
            if (targetUserId < 1) throw new ArgumentOutOfRangeException("targetUserId");

            try
            {
                SendRequest(RequestMethod.Get,
                            string.Format("https://api.twitter.com/1/{0}/{1}/subscribers/{2}.xml", screenName, listSlug,
                                          targetUserId),
                            true);
                return true;
            }
            catch (TwitterException ex)
            {
                if (ex.Message == "The specified user is not a subscriber of this list")
                {
                    return false;
                }
                throw;
            }
        }

        /// <summary>
        /// Checks if a user is a subscriber of the specified list.
        /// </summary>
        /// <param name="screenName">Screen name of the owner of the list</param>
        /// <param name="listId">The ID of the target list</param>
        /// <param name="targetUserId">The user ID of the potential list subscriber</param>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>True if the user is a subscriber of the list, otherwise false</returns>
        public bool IsUserSubscriberOfList(string screenName, ulong listId, ulong targetUserId)
        {
            if (string.IsNullOrEmpty(screenName)) throw new ArgumentNullException("screenName");
            if (targetUserId < 1) throw new ArgumentOutOfRangeException("targetUserId");
            if (listId < 1) throw new ArgumentOutOfRangeException("targetUserId");

            try
            {
                SendRequest(RequestMethod.Get,
                            string.Format("https://api.twitter.com/1/{0}/{1}/subscribers/{2}.xml", screenName, listId,
                                          targetUserId),
                            true);
                return true;
            }
            catch (TwitterException ex)
            {
                if (ex.Message == "The specified user is not a subscriber of this list")
                {
                    return false;
                }
                throw;
            }
        }

        /// <summary>
        /// Checks if a user is a subscriber of the specified list.
        /// </summary>
        /// <param name="list">Target list</param>
        /// <param name="target">User to check</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <returns>True if the user is a subscriber of the list, otherwise false</returns>
        public bool IsUserSubscriberOfList(TwitterList list, TwitterUser target)
        {
            if (list == null) throw new ArgumentNullException("list");
            if (target == null) throw new ArgumentNullException("target");

            return IsUserSubscriberOfList(list.Owner.ScreenName, list.Id, target.UserId);
        }

        #endregion
    }
}
